package com.geostar.constructionland.index.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.geostar.constructionland.index.entity.*;
import com.geostar.constructionland.index.entity.model.IndexCancelModel;
import com.geostar.constructionland.index.entity.model.LandUseIndexAddModel;
import com.geostar.constructionland.index.entity.model.LandUseIndexDelModel;
import com.geostar.constructionland.index.mapper.*;
import com.geostar.constructionland.index.service.IndexCancelService;
import com.geostar.constructionland.index.service.LandUseIndexService;
import com.geostar.constructionland.index.util.CommonUtils;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 用地指标信息表
 */
@Service
public class LandUseIndexSerImpl implements LandUseIndexService {

    @Resource
    LandUseIndexMapper landUseIndexMapper;
    @Resource
    BusinessLogMapper businessLogMapper;
    @Resource
    AttachmentInfoMapper attachmentInfoMapper;
    @Resource
    BusinessRelationshipMapper businessRelationshipMapper;
    @Resource
    InxOutStorageAcotMapper inxOutStorageAcotMapper;
    @Resource
    IndexCancelService indexCancelService;

    /**
     * 新增用地指标
     * @param landUseIndexAddModel
     */
    @Override
    @Transactional
    public void insertLandUseIndex(LandUseIndexAddModel landUseIndexAddModel) {
        List<LandUseIndexEntity> landUseIndexes = landUseIndexAddModel.getLandUseIndexes();
        String businessId = landUseIndexAddModel.getBusinessId();
        String attachmentDirId = landUseIndexAddModel.getAttachmentDirId();
        String userid = landUseIndexAddModel.getUserid();
        String username = landUseIndexAddModel.getUsername();
        // 查询用地指标
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("ywid", businessId);
        List<LandUseIndexEntity> landUseIndexList = landUseIndexMapper.selectByMap(columnMap);
        // 删除不匹配的用地指标
        List<String> landUseIndexIdList = new ArrayList<>();
        if (landUseIndexList.size() > 0) {
            for (LandUseIndexEntity landUseIndex1 : landUseIndexList) {
                // 删除标志
                boolean delFlag = true;
                for (LandUseIndexEntity landUseIndex2 : landUseIndexes) {
                    if (landUseIndex1.getId().equals(landUseIndex2.getId())) {
                        delFlag = false;
                        landUseIndexMapper.updateById(landUseIndex2);
                    } else {
                        landUseIndexMapper.insert(landUseIndex2);
                    }
                }
                if (delFlag) {
                    landUseIndexIdList.add(landUseIndex1.getId());
                }
            }
        }
        if (landUseIndexIdList.size() > 0) {
            LandUseIndexDelModel landUseIndexDelModel = new LandUseIndexDelModel();
//            landUseIndexDelModel.setLandUseIndexId(StringUtils.join().join(landUseIndexIdList, ","));
            landUseIndexDelModel.setBusinessId(businessId);
            landUseIndexDelModel.setAttachmentDirId(attachmentDirId);
            landUseIndexDelModel.setUserid(userid);
            landUseIndexDelModel.setUsername(username);
            deleteLandUseIndex(landUseIndexDelModel);
        }
    }

    /**
     * 删除用地指标
     * @param landUseIndexDelModel
     */
    @Override
    @Transactional
    public void deleteLandUseIndex(LandUseIndexDelModel landUseIndexDelModel) {
        String landUseIndexId = landUseIndexDelModel.getLandUseIndexId();
        String businessId = landUseIndexDelModel.getBusinessId();
        String attachmentDirId = landUseIndexDelModel.getAttachmentDirId();
        // 保存业务日志
        saveBusinessLog(landUseIndexDelModel);
        Map<String, Object> landUseIndexMap = new HashMap<>();
        Map<String, Object> businessRelationshipMap = new HashMap<>();
        String[] landUseIndexIdArr = landUseIndexId.split(",");
        for (String id : landUseIndexIdArr) {
            businessRelationshipMap.put("zbid", id);
            landUseIndexMap.put("zbid", id);
        }
        // 获取附件的关联关系
        List<BusinessRelationshipEntity> businessRelationshipList = businessRelationshipMapper.selectByMap(businessRelationshipMap);
        List<String> attachmentIdList = new ArrayList<>();
        for (BusinessRelationshipEntity businessRelationship : businessRelationshipList) {
            attachmentIdList.add(businessRelationship.getSideTableId());
        }
        // 删除附件
        if (attachmentIdList.size() > 0) {
            UpdateWrapper<AttachmentInfoEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("fjid", attachmentIdList);
            updateWrapper.eq("ywid", businessId);
            updateWrapper.eq("fjmlid", attachmentDirId);
            updateWrapper.eq("scbz", 0);
            AttachmentInfoEntity attachmentInfo = new AttachmentInfoEntity();
            attachmentInfo.setDeleteFlag(1);
            attachmentInfoMapper.update(attachmentInfo, updateWrapper);
        }
        // 删除附件的关联关系
        businessRelationshipMapper.deleteByMap(businessRelationshipMap);
        // 删除用地指标
        landUseIndexMapper.deleteByMap(landUseIndexMap);
    }

    /**
     * 更新指标出库台账信息
     * @param landUseIndexAddModel
     */
    @Override
    @Transactional
    public void updateInxOutStorageAcot(LandUseIndexAddModel landUseIndexAddModel) {
        List<LandUseIndexEntity> landUseIndexes = landUseIndexAddModel.getLandUseIndexes();
        String businessId = landUseIndexAddModel.getBusinessId();
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("ywid", businessId);
        List<InxOutStorageAcotEntity> inxOutStorageAcotList = inxOutStorageAcotMapper.selectByMap(columnMap);
        if (inxOutStorageAcotList.size() > 0) {
            IndexCancelModel indexCancelModel = new IndexCancelModel();
            indexCancelModel.setBusinessId(businessId);
            indexCancelModel.setOperatorId(landUseIndexAddModel.getUserid());
            if (inxOutStorageAcotList.size() != landUseIndexes.size()) {
                indexCancelModel.setCancelReason("出库台账记录与用地指标记录的数量不一致");
                indexCancelService.cancelIndex(indexCancelModel);
                return;
            } else {
                int num = 0;
                for (LandUseIndexEntity landUseIndexEntity : landUseIndexes) {
                    for (InxOutStorageAcotEntity inxOutStorageAcotEntity : inxOutStorageAcotList) {
                        if (landUseIndexEntity.getInxStorageIAcotId().equals(inxOutStorageAcotEntity.getInxStorageIAcotId())) {
                            num++;
                            if (landUseIndexEntity.getAddIndex().compareTo(inxOutStorageAcotEntity.getBuildLandAdd()) != 0
                                    || landUseIndexEntity.getAgclLandIndex().compareTo(inxOutStorageAcotEntity.getAgclLand()) != 0
                                    || landUseIndexEntity.getFarmlandIndex().compareTo(inxOutStorageAcotEntity.getFarmland()) != 0) {
                                indexCancelModel.setCancelReason("出库台账记录与用地指标记录的新增指标、农用地指标、耕地指标不一致");
                                indexCancelService.cancelIndex(indexCancelModel);
                                return;
                            }
                        }
                    }
                }
                if(inxOutStorageAcotList.size() != num) {
                    indexCancelModel.setCancelReason("出库台账记录与用地指标记录的入库ID不一致");
                    indexCancelService.cancelIndex(indexCancelModel);
                    return;
                }
            }
        }
    }

    /**
     * 保存业务日志
     */
    private void saveBusinessLog(LandUseIndexDelModel landUseIndexDelModel) {
        BusinessLogEntity businessLog = new BusinessLogEntity();
        businessLog.setId(CommonUtils.getUUID());
        businessLog.setBusinessId(landUseIndexDelModel.getBusinessId());
        businessLog.setOperatorId(landUseIndexDelModel.getUserid());
        businessLog.setOperatorName(landUseIndexDelModel.getUsername());
        businessLog.setOperateTime(new Date());
        // 用地指标删除
        businessLog.setOperateType("YDZBSC");
        Map<String, Object> columnMap = new HashMap<>();
        String landUseIndexId = landUseIndexDelModel.getLandUseIndexId();
        String[] landUseIndexIdArr = landUseIndexId.split(",");
        for (String id : landUseIndexIdArr) {
            columnMap.put("zbid", id);
        }
        List<LandUseIndexEntity> landUseIndexList = landUseIndexMapper.selectByMap(columnMap);
        String resultJson = "";
        if (landUseIndexList.size() > 0) {
            resultJson = JSONObject.toJSONString(landUseIndexList);
        }
        businessLog.setOperateContent(resultJson.getBytes(StandardCharsets.UTF_8));
        businessLogMapper.insert(businessLog);
    }
}
